package cn.school.workflow.listener;

import cn.school.sys.dao.SysUserDao;
import cn.school.workflow.dao.QuitApplyDao;
import cn.school.workflow.vo.QuitApplyVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class PrincipalListener implements TaskListener {

    private static final long serialVersionUID = 3584534949275898923L;
    @Autowired
    private QuitApplyDao quitApplyDao;
    @Autowired
    private SysUserDao sysUserDao;

    @Override
    public void notify(DelegateTask delegateTask) {
        setQuitCurrApprovedBy(delegateTask);
    }
    /**
     * 设置离职申请审批人
     * @param delegateTask
     */
    private void setQuitCurrApprovedBy(DelegateTask delegateTask) {
        LambdaQueryWrapper<QuitApplyVO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(QuitApplyVO::getProcessId, delegateTask.getProcessInstanceId());
        QuitApplyVO applyVO = new QuitApplyVO();
        if(delegateTask.getTaskDefinitionKey().equals("inChargePrincipal")){//分管校长
            List<String> list = sysUserDao.findDeptLeaderApprovalUserByDeptName("分管校长");
            Map<String,Object> variables = new HashMap<>();
            variables.put("assignee", StringUtils.join(list,","));
            delegateTask.setVariables(variables);
            //回写流程当前审批人
            applyVO.setCurrApprovedBy(StringUtils.join(list,","));
            quitApplyDao.update(applyVO,wrapper);
        }
        if(delegateTask.getTaskDefinitionKey().equals("executePrincipal")){//执行校长
            List<String> list = sysUserDao.findDeptLeaderApprovalUserByDeptName("执行校长");
            Map<String,Object> variables = new HashMap<>();
            variables.put("assignee", StringUtils.join(list,","));
            delegateTask.setVariables(variables);
            //回写流程当前审批人
            applyVO.setCurrApprovedBy(StringUtils.join(list,","));
            quitApplyDao.update(applyVO,wrapper);
        }
    }
}
